<template>
	<view class="bizPage">
		<status-bar title="考勤统计" />
		<view class="head bgwhite flexac" :style="{top: totalHeight + 'px'}">
			<view class="tabs padding4 d-flex j-sb">
				<view class="item flexac size24 color-666" :class="{'bgwhite color-222': current == index}" @click="pageChange(index)" 
					v-for="(item,index) in ['日','周','月']" :key="index">{{ item }}</view>
			</view>
		</view>
		<view class="padding20 m-top90">
			<block v-if="current == 0">
				<view class="card">
					<uni-calendar :insert="true" :selected="selected" :showMonth="false" width="90rpx" :diy="true" @change="dateChange" @monthSwitch="monthSwitch" />
				</view>
				<view class="card">
					<block v-if="logList.length">
						<view class="d-flex a-center p-re" :class="{'start': index != logList.length - 1}" v-for="(item,index) in logList" :key="index">
							<view class="size48 color-222 bold t-letter2">{{ item.realTime.slice(-8, -3) }}</view>
							<view class="flex-1 m-left40">
								<view class="ellipsis_1 m-bot10">
									<text class="size28 color-222 bold">{{ item.type == 1 ? '上班' : '下班' }} · </text>
									<text class="size24 color-666">{{ item.adcAddr }}</text>
								</view>
								<view class="size24 color-999">{{ item.descri }}</view>
							</view>
						</view>
					</block>
					<up-empty :show="noData" mode="history" iconSize="60" text="无打卡记录"></up-empty>
				</view>
			</block>
			<block v-else>
				<view class="card d-flex a-center">
					<image class="avatar m-right20" :src="imgUrls(mainStore.userInfo.avatar)" mode="aspectFill"></image>
					<view class="flex-1">
						<view class="size30 color-333 bold m-bot10">{{ mainStore.userInfo.userName }}</view>
						<view class="size28 color-999">{{ mainStore.userInfo.position }}</view>
					</view>
					<view class="size26 color-999">{{ setFormat('yyyy年mm月dd日') }}</view>
				</view>
				<view class="card" style="padding: 40rpx 0;">
					<view class="p-left40 p-right40">
						<view class="row m-bot48" v-if="current == 1">
							<view class="week flexac size28" :class="{'active': weekIndex == index}" @click="changeWeek(index)" v-for="(item,index) in weeks" :key="index">第{{ units[index] }}周</view>
						</view>
						<date-switch @getDate="monthSwitch" v-if="current == 2" />
						<view class="size32 color-222 bold m-bot40">上下班打卡</view>
					</view>
					<ring :raw-data="ringData" />
				</view>
				<view class="card" style="padding: 30rpx;">
					<view class="size32 color-222 bold m-bot60">假勤/次</view>
					<view class="d-flex j-sa">
						<view class="text-center" v-for="(item,index) in list" :key="index">
							<view class="size28 color-222 bold m-bot20">{{ pageData[item.key] }}</view>
							<view class="size24 color-666">{{ item.name }}</view>
						</view>
					</view>
				</view>
			</block>
		</view>
		
		<tab-bar source="clockIn" width="40" />
	</view>
</template>

<script setup>
	import { ref, computed } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useMainStore } from '@/stores/index'
	import { Toast, imgUrls } from '@/utils/utils.js'
	import Http from '@/utils/request.js'
	import statusBar from '../components/statusBar.vue'
	import tabBar from '../components/tabBar.vue'
	import ring from '../components/ring.vue'
	import dateSwitch from '../components/dateSwitch.vue'
	
	const mainStore = useMainStore()
	const totalHeight = computed(() => {
		return mainStore.statusBarHeight + mainStore.navBarHeight
	})

	const current = ref(0)
	const month = ref('')
	const day = ref('')

	onLoad(() => {
		month.value = setFormat('yyyy-mm')
		day.value = setFormat('yyyy-mm-dd')
		getLog()
		getResult()
		getCount()
	})

	const pageData = ref('')
	const list = ref([
		{ name: '请假', key: 'leaveCount' },
		{ name: '补卡', key: 'makeUpClockInCount' },
		{ name: '外出', key: 'outOfOfficeCount' },
		{ name: '出差', key: 'businessTripCount' },
		{ name: '外勤', key: 'fieldWorkCount' }
	])
	const ringData = ref([
		{ name: '正常打卡', key: 'normalClockInCount' },
		{ name: '迟到', key: 'lateCount' },
		{ name: '早退', key: 'earlyLeaveCount' },
		{ name: '旷工', key: 'absentCount' }
	])

	// 按月
	const getCount = () => {
		Http.get({
			url: '/hr/adc/getAbnList',
			data: {
				month: month.value
			}
		}).then(res => {
			updateData(res)
		})
	}

	// 按周
	const getWeekCount = () => {
		let { weekStart, weekEnd } = weeks.value[weekIndex.value]
		Http.get({
			url: '/hr/adc/getAbnListByWeek',
			data: {
				weekStart,
				weekEnd
			}
		}).then(res => {
			updateData(res)
		})
	}

	const updateData = (res) => {
		if(res.code != 0) return Toast(res.msg)
		pageData.value = res.data || ''
		ringData.value.forEach(item => {
			item.value = Number(pageData.value[item.key] || '')
			item.labelText = item.name + ' ' + item.value + '天'
		})
	}

	const logList = ref([])
	const noData = ref(false)
	
	// 每日打卡记录查询
	const getLog = () => {
		Http.get({
			url: '/hr/adc/getAdcListByDay',
			data: {
				day: day.value
			}
		}).then(res => {
			logList.value = []
			if(res.code != 0) return Toast(res.msg)
			let result = res.data || ''
			if(result.work) logList.value.push(result.work)
			if(result.offWork) logList.value.push(result.offWork)
			noData.value = logList.value.length ? false : true
		})
	}

	// 打点
	const selected = ref([])

	// 每日考勤结果查询
	// 0未打卡、10正常、21迟到、22早退、23缺卡、30非上班日正常打卡、31非上班日迟到、32非上班日早退、40请假、50调休
	const getResult = () => {
		Http.get({
			url: '/hr/adc/getMthResultOfDay',
			data: {
				month: month.value
			}
		}).then(res => {
			selected.value = []
			if(res.code != 0) return Toast(res.msg)
			let result = res.data || []
			result.forEach(item => {
				if(item.adcable) { // 工作日
					if(isDateBeforeToday(item.adcDay)) {
						selected.value.push({
							date: item.adcDay,
							type: item.workRes == 10 && item.offdutyRes == 10 ? 'normal' : 'abnormal'
						})
					}
				} else { // 休息
					if(item.workRes == 30 && item.offdutyRes == 30) {
						selected.value.push({
							date: item.adcDay,
							type: 'normal'
						})
					}
				}
			})
		})
	}
	
	const isDateBeforeToday = (dateString) => {
		const today = new Date()
		const targetDate = new Date(dateString)
		return targetDate < today
	}

	const pageChange = (index) => {
		month.value = setFormat('yyyy-mm')
		if(index == 0) {
			day.value = setFormat('yyyy-mm-dd')
			getLog()
			getResult()
		}
		if(index == 1) {
			let arr = month.value.split('-')
			weeks.value = getWeeksInMonth(arr[0], arr[1])
			getWeekCount()
		}
		if(index == 2) getCount()
		setTimeout(() => {
			current.value = index
		}, 100)
	}

	const dateChange = (e) => {
		console.log(e)
		day.value = e.fulldate
		getLog()
	}

	const monthSwitch = (e) => {
		month.value = e.year + '-' + e.month.toString().padStart(2, '0')
		if(current.value == 0) getResult()
		if(current.value == 2) getCount()
	}

	const setFormat = (format) => {
		return uni.$u.timeFormat(Number(new Date()), format)
	}

	const weeks = ref([])
	const weekIndex = ref(0)
	const units = ref(['一','二','三','四','五'])

	const changeWeek = (index) => {
		weekIndex.value = index
		getWeekCount()
	}

	// 计算某月周数及每周日期范围
	const getWeeksInMonth = (year, month) => {
	  	const weeks = []
		const firstDay = new Date(year, month - 1, 1)
		const lastDay = new Date(year, month, 0)
	  	// 找到第一个周一
		let currentMonday = new Date(firstDay)
		currentMonday.setDate(currentMonday.getDate() - ((currentMonday.getDay() + 6) % 7))
	  	while (true) {
			const currentSunday = new Date(currentMonday)
			currentSunday.setDate(currentSunday.getDate() + 6)
			// 检查周天是否在当前月内
			if (currentSunday <= lastDay) {
				weeks.push({
					weekStart: uni.$u.timeFormat(new Date(currentMonday), 'yyyy-mm-dd'),
					weekEnd: uni.$u.timeFormat(new Date(currentSunday), 'yyyy-mm-dd')
				})
			}
			currentMonday.setDate(currentMonday.getDate() + 7)
			// 如果当前周一超过最后一天则结束循环
			if (currentMonday > lastDay) break
		}
	  	return weeks
	}
</script>

<style lang="scss" scoped>
	.bizPage {
		min-height: 100vh;
		background: #F6F7FB;
	}
	.head {
		width: 100%;
		height: 90rpx;
		position: fixed;
		left: 0;
		z-index: 11;
		.tabs {
			width: 226rpx;
			height: 64rpx;
			background: #F6F7FB;
			border-radius: 10rpx;
			.item {
				width: 58rpx;
				height: 58rpx;
				border-radius: 10rpx;
			}
		}
	}      
	.card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
		.start {
			margin-bottom: 80rpx;
			&::after {
				content: '';
				width: 2rpx;
				height: 60rpx;
				background: #CFD7DE;
				position: absolute;
				left: 60rpx;
				bottom: -70rpx;
			}
		}
		.avatar {
			width: 66rpx;
			height: 66rpx;
			border-radius: 10rpx;
		}
		.week {
			width: 130rpx;
			height: 60rpx;
			border-radius: 30rpx;
			margin: 0 18px 12px 0;
			&:nth-child(4n) {
				margin-right: 0;
			}
			&.active {
				background: v-bind('mainStore.color');
				color: #fff;
			}
		}
	}
</style>
